package cn.hiapi.shopkeeper.service.order;

import cn.hiapi.basic.exception.BasicException;
import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.service.AbsBasicService;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.shopkeeper.entity.activity.Activity;
import cn.hiapi.shopkeeper.entity.order.ActivityOrder;
import cn.hiapi.shopkeeper.entity.order.MyActivityOrder;
import cn.hiapi.shopkeeper.enums.ActivityType;
import cn.hiapi.shopkeeper.jpa.order.MyActivityOrderJpa;
import cn.hiapi.shopkeeper.service.activity.ActivityService;
import cn.hiapi.shopkeeper.service.activity.IActivityStatusEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author AdinZ
 * @date 2023/1/2 20:51
 */
@Service
public class MyActivityOrderService extends AbsBasicService<MyActivityOrderJpa, MyActivityOrder, Long> implements IActivityStatusEvent {

    private final DispatchContext dispatchContext;

    public MyActivityOrderService(DispatchContext dispatchContext) {
        this.dispatchContext = dispatchContext;
    }


    /**
     * 支付成功,创建我的服务
     *
     * @param order
     */
    @Transactional
    public void payCallback(ActivityOrder order) {

        if(order.getActivityType()!= ActivityType.CARD)return;
        Activity activity = this.dispatchContext.getServiceOne(ActivityService.class).get(order.getAid());
        if (activity == null) throw new BasicException("活动不存在");

        MyActivityOrder activityOrder = new MyActivityOrder();
        activityOrder.setActivityType(order.getActivityType());
        activityOrder.setPrice(order.getPrice());
        activityOrder.setBuyerId(order.getBuyerId());
        activityOrder.setAid(order.getAid());
        activityOrder.setOid(order.getId());
        activityOrder.setCostPrice(order.getCostPrice());
        activityOrder.setThumb(order.getThumb());
        activityOrder.setTitle(order.getTitle());
        activityOrder.setShopId(order.getShopId());
        activityOrder.setStartTime(activity.getStartTime());
        activityOrder.setEndTime(activity.getEndTime());
        this.save(activityOrder);
    }

    @Override
    @Transactional
    public void activityChange(List<Activity> list) {
        for (Activity activity : list) {
            if (activity.getStatus() != 2) continue;
            List<MyActivityOrder> orders = this.findList(new QueryWrapper().eq("status", 0).eq("aid", activity.getId()));
            orders.forEach(e -> {
                e.setStatus(2);
                e.setUpdated(System.currentTimeMillis());
            });
            this.save(orders);
        }
    }

    @Override
    public void activityUseEnd(List<Activity> list) {

    }
}
